var config = require('../../common/config');
var global = require('../../common/global');
var request = require('request');
var utils = require('../../common').utils;
var _ = require('underscore');

var reqTemplate = config.reqTemplate;
var logger = config.logger('app');

exports.loginPage = function (req, res) {
    res.render('driverLogin.hbs', null);
};

exports.login = function (req, res) {
    var option = new reqTemplate("partner?filter=" + JSON.stringify({where: req.body}), "GET");
    request(option, function (err, response) {
        if (err) {
            logger.error(err.stack);
            res.send(response || err);
        } else {
            var obj = eval("(" + response.body + ")");
            if (obj.length === 1) {
                res.cookie('uuId', "exist", {path: '/driver'});
                res.cookie('userId', obj[0].id, {path: '/driver'});
                res.cookie('userName', obj[0].username, {path: '/driver'});
                res.send('success');
            } else {
                res.send("error");
            }
        }
    });
};

exports.modifyAccount = function (req, res) {
    var user = utils.generateCookie(req.headers.cookie);
    var option = new reqTemplate("user/" + user.userId, "PUT");
    option.form = _.extend(option.form, req.body);
    option.headers.authorization = user.uuId;
    request(option, function (err, response) {
        if (err) {
            logger.error(err.stack);
            res.send(response || err);
        } else {
            res.send(eval("(" + response.body + ")"));
        }
    });
};

exports.driverIndexPage = function (req, res) {
    var user = utils.generateCookie(req.headers.cookie);
    if(!user.userId) {
        res.redirect("/driver/login");
    }
    var option = new reqTemplate("partner/" + user.userId, "GET");
    option.form = _.extend(option.form, req.body);
    request(option, function (err, response) {
        if (err) {
            logger.error(err.stack);
            res.send(response || err);
        } else {
            var obj = eval("(" + response.body + ")");
            obj.server_url = process.env.NODE_SERVER;
            res.render('driverIndex.hbs', obj);
        }
    });
};

exports.fetchOrder = function (req, res) {
    var user = utils.generateCookie(req.headers.cookie);
    if (!user || !user.userId) {
        res.redirect("/driver/login");
        return;
    }

    //0. check if exits 1.match car type 2.set/delete in global 3.write status and info to db 4.send customer info
    //实现0-3后
    console.log("Grab : " + req.body.orderId);
    if (!!global.orders[req.body.orderId]) {
        var order = global.orders[req.body.orderId];
        if (!!global.customers[order.user_id]) {
            if (!global.drivers[user.userId]) {
                logger.info("Driver Offline");
            }
            global.customers[order.user_id].emit("orderEnsure", {driver: global.drivers[user.userId]});
            global.customers[order.user_id] = false;
            res.send({order : order});
        } else {
            logger.info("User Offline");
            global.customers[order.user_id] = false;
            res.send({order : order});
        }
        global.orders[req.body.orderId] = undefined;
        //todo write to db.
        logger.info("Order Grabbed. Remove Order");
    } else {
        res.send("订单已被抢走或取消"); //todo CANCEL ORDER, SYNC IN GLOBAL
    }
};